package net.sf.google.talk.eclipse.views;

import java.io.File;

import net.sf.google.talk.eclipse.EclipsePlugin;
import net.sf.google.talk.eclipse.preferences.GTalkPreferencePage;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.preference.IPreferenceStore;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

public class IncomingFileJob extends Job {

	private FileTransferRequest req;
	private File incomingFile;
	private final IncomingFileTransfer ift;
	
	public IncomingFileJob(final FileTransferRequest r) {
		super("Receiving file "+r.getFileName()+"("+r.getFileSize()+")");
		System.out.println("Creating job");
		this.req = r;
		
		String incomingFileName = r.getFileName();
		IPreferenceStore store = EclipsePlugin.getDefault().getPreferenceStore();
		String incomingDir = store.getString(GTalkPreferencePage.INCOMING_DIR);
		
		// the file that incoming
		incomingFile = new File(incomingDir + System.getProperties().getProperty("file.separator") + incomingFileName);
		
		System.out.println("incomingFile: "+incomingFile);
		
		ift = req.accept();
	}

	@Override
	protected IStatus run(final IProgressMonitor monitor) {
		// TODO Auto-generated method stub
		try {
			System.out.println("starting reception");
			monitor.beginTask("Receiving "+ift.getFileName(), (int) ift.getFileSize());
			ift.recieveFile(incomingFile);
			long written = 0;
			while (!ift.isDone()) {
				if (monitor.isCanceled()) {
					ift.cancel();
				}
				long written2 = ift.getAmountWritten();
				long delta = written - written2;
				monitor.worked((int) delta);
				written = written2;
			}
			System.out.println("done");
			monitor.done();
			// TODO: how to monitor transfer as described in javadoc???
			
//			log.log(new Status(Status.INFO, EclipsePlugin.ID, Status.OK, "Received file "+ift.getFileName()+" and stored in  "+ift.getFilePath(), null));
//			getSite().getShell().getDisplay().asyncExec(new Runnable() {
//				public void run() {
//					MessageDialog.openInformation(getSite().getShell(), "Incoming file", "The File "+ift.getFileName()+" was received and stored in  "+ift.getFilePath() );
//				}
//			});

			
		} catch (XMPPException e) {
			System.out.println("Error: could not receive file!");
			e.printStackTrace();
			return new Status(Status.ERROR, EclipsePlugin.ID, Status.ERROR, "Error receiving file "+req.getFileName(), e);
		}

		return Status.OK_STATUS;
	}

}
